import { Injectable } from '@nestjs/common';
import { hash,verify } from 'argon2';
import { PrismaService } from 'src/prisma/prisma.service';
import RegisterDto from './dto/register.dto';
import LoginDto from './dto/login.dto';
import { JwtService } from '@nestjs/jwt';

@Injectable()
export class AuthService {
  constructor(private readonly prisma: PrismaService ,private jwt:JwtService) {}

  /**
   * 注册用户
   * @param dto 
   */
 async register(dto:RegisterDto) {
      const password =await hash(dto.password);
      const user = await this.prisma.user.create({
        data: {
          name: dto.name,
          password,
          password_confirm: dto.password_confirm,
        },
      });
 
    return user;
  }
  /**
   * 登录
   * @param dto 
   */
   async login(dto:LoginDto) {
    const user = await this.prisma.user.findFirst({
      where: {
        name: dto.name,
      },
    });
    if (!user) {
      return {
        message: '用户不存在',
      };
    }
    // 校验密码
    const isPasswordValid = await verify(user.password as any, dto.password);
    if (!isPasswordValid) {
      return {
        message: '密码错误',
      };
    } 
    return this.token(user);

  }
   private async token({name,id}){
    return {
      token:await this.jwt.signAsync({name,sub:id}),
    }
  }
}
